<template>
  <div :class="!callScreen?'business-history-table':''">
    <div class="title">
      {{titleName}}
    </div>
    <div class="wrap">
      <el-row>
        <el-col class="history-business-num" :span="24">
          {{$t('business.countRecord', {count: tableData.count})}}
        </el-col>
      </el-row>
      <time-line :items="tableData.list" timeKey="createTime">
        <el-row
          class="history-wrap"
          slot="item"
          slot-scope="props">
          <el-col :span="24">
            <el-tooltip :open-delay="150"
                        placement="right" popper-class="business-history-wap" :visibleArrow="false" effect="light" transition="fade-leave">
              <div slot="content" class="card-detail"
                   v-loading="toolTipLoad"
                   element-loading-background="rgba(0, 0, 0, 0)">
                <div class="card-detail-tittle" v-show="!toolTipLoad">{{$t('business.businessContent')}}</div>
                <table>
                  <tbody valign="top">
                  <template v-for="(i,index) in toolTipObj[props.item._id] || []">
                    <tr class="card-detail-item">
                      <td class="data-name">{{i.name}}</td>
                      <td class="break-all">{{i.value}}</td>
                    </tr>
                  </template>
                  </tbody>
                </table>
              </div >
              <div @click.stop="businessDetail(props.item._id)" class="history-title" @mouseenter="mouseenterToolTip(props.item._id)">
                <span class="font14">{{props.item.businessTypeName}}</span>
                <span class="history-title-detail">{{$t('public.intelDetails')}}</span>
              </div>
            </el-tooltip>
            <div class="state process fr" v-if="!props.item.dispose">{{$t('business.dealing')}}</div>
            <div class="state finish fr" v-else>{{$t('business.complete')}}</div>
          </el-col>
          <el-col :span="24">
            <table class="history-content">
              <tbody>
              <tr>
                <td class="name">{{$t('business.businessNumber')}}</td>
                <td class="value">{{props.item.number}}</td>
              </tr>
              <tr>
                <td class="name">{{$t('public.createTime')}}</td>
                <td class="value">{{props.item.createTime}}</td>
              </tr>
              <tr>
                <td class="name">{{$t('monitor.createAgent')}}</td>
                <td class="value">{{props.item.agentName}}</td>
              </tr>
              <tr>
                <td class="name">{{$t('business.currentStep')}}</td>
                <td class="value step">{{props.item.disposeDisplay}}</td>
              </tr>
              <tr>
                <td class="name">{{$t('business.master')}}</td>
                <td class="value">{{props.item.masterName ? props.item.masterName: "----"}}</td>
              </tr>
              <tr>
                <td class="name">{{$t('business.recentUpdatedTime')}}</td>
                <td class="value">{{props.item.lastUpdateTime}}</td>
              </tr>
              </tbody>
            </table>
          </el-col>
        </el-row>
      </time-line>
      <el-row>
        <el-col :span="24" class="next-page" v-if="isLoadMoreShow">
          <div class="btn" @click.stop="loadMore">{{$t('public.loadMore')}}</div>
        </el-col>
      </el-row>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll :title="$t('business.businessHistoryDetail')" :visible.sync="detailShow" :width="callScreen?'70%':'800px'" :modal="callScreen?false:true" @close="off">
      <business class="business-dialog" :busId="busId" :cacheId="cacheId" :showHistory="true" v-if="detailShow" v-on:event="businessEvent" :callScreen="true" :isWebchat='true' :relatedBusinessShow="false"></business>
    </el-dialog>
  </div>
</template>
<script>
  import TimeLine from '../../../../ui-modules/affix/TimeLineSmall'
  import business from '../index.vue'
  import {sortBusinessFields, getStartStep} from '@/utils/workflowUtils'
  export default {
    name: 'BusinessHistoryTable',
    data () {
      return {
        toolTipLoad: false,
        toolTipObj: {},
        isLoadMoreShow: false,
        data: {
          customer: this.cid,
          type: 'business',
          page: 1,
          limit: 20
        },
        tableData: {
          count: 0,
          list: []
        },
        loading: true,
        busId: '',
        detailShow: false,
        currToolTipId: ''
      }
    },
    props: {
      cid: String,
      titleName: String,
      type: String,
      cacheId: {type: String, default: ''}, // 缓存工单信息的id
      callScreen: Boolean,
      // 关联工单
      businessNumbers:{
        type: Array,
        default: () => []
      }
    },
    computed: {
      refreshHistoryTable () {
        return this.$store.state.business.transCache.refreshCustomerBusinessHistory
      }
    },
    watch: {
      refreshHistoryTable () {
        if (this.refreshHistoryTable.customer === this.cid && this.loading) {
          this.data.page = 1
          this.tableData.list = []
          this.loading = false
          this.fetchData()
        }
      }
    },
    components: {
      business,
      TimeLine
    },
    methods: {
      businessType (item) {
        let businessFlows = this.$getCache('businessFlow') || []
        for (let i = 0; i < businessFlows.length; i++) {
          if (businessFlows[i]._id === item.flow) {
            let {fields} = businessFlows[i]
            let step = getStartStep(businessFlows[i])
            let stepFields = step.stepFields || []
            let detail = [{name: this.$t('business.businessNumber'), value: item.number}]
            sortBusinessFields(stepFields, fields, item, detail, 'card')
            return detail
          }
        }
        return []
      },
      loadMore () {
        this.data.page++
        this.fetchData()
      },
      backHistory () {
        this.$emit('backHistory', false)
      },
      businessEvent (eventData) {
        if (eventData.event !== 'changeBusinessMaster') {
          this.$store.dispatch('getBusinessDetailById', {_id: this.busId})
        }
        this.$store.commit('business/REFRESH_CUSTOMER_BUSINESS_HISTORY', this.cid)
      },
      fetchData () {
        this.data.customer = this.cid
        // 关联工单
        if(this.type === 'related'){
          let data = {"number":{"$in":this.businessNumbers}}
          this.$store.dispatch('queryAllBusiness', data).then((res) => {
            if (res && res.success) {
              if (res.list.length === 0) {
                this.tableData.list = []
              }else{
                const getListItemById = (list, id) => {
                  for (let i = 0; i < list.length; i++) {
                    if (list[i]._id === id) {
                      return list[i]
                    }
                  }
                }
                Promise.all([
                  this.$store.dispatch('getCache', { type: 'agents' }),
                  this.$store.dispatch('getCache', { type: 'businessFlow' }),
                  this.$store.dispatch('getCache', { type: 'businessFlowStep' })
                ]).then(([agents, businessFlows, businessFlowSteps]) => {
                  // 处理列表数据
                  res.list.forEach(item=>{
                    // 创建人
                    let agentObj = getListItemById(agents, item.createUser || '')
                    let agentName = agentObj ? (agentObj.displayName ? agentObj.displayName + agentObj.exten : '') : ''
                    item.agentName = agentName
                    // 当前工单
                    let businessTypeName = ''
                    let businessFlow = getListItemById(businessFlows, item.flow)
                    businessTypeName = businessFlow ? (businessFlow.name ? businessFlow.name : '') : ''
                    item.businessTypeName = businessTypeName
                    // 当前步骤
                    let disposeDisplay = ''
                    let businessStep = getListItemById(businessFlowSteps, item.step)
                    disposeDisplay = businessStep ? (businessStep.name ? businessStep.name : '') : ''
                    item.disposeDisplay = disposeDisplay
                    if (businessStep && businessStep.type === 'sys') {
                      item.dispose = businessStep.systemFn
                    }
                  })
                  this.tableData.list = res.list
                  this.tableData.count = res.list.length
                })
              }
            }
          })
        } else {
          this.$store.dispatch('queryCustomerBusinessHistory', this.data).then(val => {
            this.tableData.count = val.count
            if (val.list.length < 20) {
              this.isLoadMoreShow = false
            } else {
              this.isLoadMoreShow = true
            }
            this.tableData.list = this.tableData.list.concat(val.list)
            this.loading = true
          })
        }
      },
      mouseenterToolTip (id) {
        console.log(id)
        console.log(this.toolTipObj)
        // store里有，直接从store 里取，否则发请求取
        if (!this.$store.state.business['current'].businessAction[id]) {
          this.toolTipLoad = true
          this.$store.dispatch('getBusinessDetailById', {_id: id, hiddenLoad: true}).then((res) => {
            if (res) {
              console.log('success')
              this.toolTipLoad = false
              this.currToolTipId = id
              let _item = this.$store.state.business['current'].businessAction[id]
              this.$set(this.toolTipObj, id, this.businessType(_item))
              console.log(this.toolTipObj)
            } else {
              console.log('error')
            }
          }).catch(() => {
            console.log('catch')
          })
        } else {
          this.toolTipLoad = false
          let _item = this.$store.state.business['current'].businessAction[id]
          this.$set(this.toolTipObj, id, this.businessType(_item))
        }
      },
      businessDetail (id) {
        this.$store.dispatch('getBusinessDetailById', {_id: id}).then((res) => {
          if (res) {
            this.detailShow = true
            this.busId = id
          } else {
            this.detailShow = false
          }
        }).catch(() => {
          this.detailShow = false
        })
      },
      off () {
        this.detailShow = false
      }
    },
    beforeMount () {
      this.data.page = 1
      this.tableData.list = []
      this.fetchData()
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../../../assets/common.styl'
  .wrap
    padding 0 20px 15px
    .history-business-num
      font-size 12px
      color $cf-gray4
      line-height 50px
      border-bottom 1px solid $c-border1
      margin-bottom 18px
  .title
    height 42px
    box-sizing border-box
    border-bottom 1px solid $c-border1
    line-height 42px
    padding 0 20px
    text-align center
    position: relative
    i
      position absolute
      left 14px
      font-size 14px
      top 13px
      &:hover
        color $c-main
        cursor pointer
  .history-title
    display inline-flex
    color $cf-gray2
    font-weight bold
    padding-bottom 10px
    &:hover
      color $c-main
      cursor pointer
    .history-title-detail
      color $c-main
      padding-left 9px
      font-size 12px
  .state
    font-size 14px
  .finish
    color $cf-gray6
  .process
    color $cf-color2
  .name
    width 72px
    color $cf-gray3
    font-size 12px
    padding-right 20px
  .value
    color $cf-gray1
    font-size 12px
    max-width 130px
    text-overflow ellipsis
    overflow hidden
    white-space nowrap
  .step
    color $c-bus-step
  .btn
    display inline-block
    padding-left 20px
    font-size 12px
    cursor pointer
    color $c-main
  .card-detail
    min-height 32px
    .card-detail-tittle
      color $cf-gray2
      font-weight bold
      padding-bottom 10px
    .card-detail-item
      line-height 22px
    .data-name
      color $cf-gray4
      min-width 50px
      width 50px
      padding-right 24px
    .break-all
      color $cf-gray2
      word-break break-all
      white-space pre-line
    .data-padding
      padding-top 15px
  /*  .history-business-num
      font-size 12px
      color $cf-gray4
      padding-bottom 26px
    .history-title
      display inline-flex
      color $cf-gray2
      font-weight bold
      &:hover
        color $c-main
        cursor pointer
      .history-title-detail
        color $c-main
        padding-left 9px
        font-size 12px
    .history-wrap
      padding 12px 10px
      border-radius 5px
    .number
      color $cf-gray4
    .state
      padding-top 5px
      font-size 14px
    .finish
      color $cf-gray6
    .process
      color $cf-color2
    .history-content
      float right
      display flex
      justify-content flex-start
      p
        color $cf-gray4
        font-size 12px
        padding-bottom 1px
        max-width 130px
      .business-name
        font-size 14px
        color $cf-gray4
        padding-bottom 6px
    .btn
      display inline-block
      padding-left 20px
      margin-left 167px
      font-size 12px
      cursor pointer
      color $c-main
    .arrow-icon
      width 175px
      display flex
      margin-top 6px
      justify-content space-between
      padding-right 10px
      span
        display block
      .dot
        width 4px
        height 4px
        border-radius 2px
        background #9b9b9b
      .arrow
        margin-top -3px
        width 6px
        height 6px
        border-top 2px solid #9b9b9b
        border-right 2px solid #9b9b9b
        transform rotate(45deg)*/
</style>
